<template>
  <div class="pagination">
    <button @click="changePageNum(pageNo - 1)" :disabled="pageNo === 1">上一页</button>
    <button @click="changePageNum(1)" v-if="startEnd.start !== 1">1</button>
    <span v-if="startEnd.start > 2">···</span>

    <!-- <button>{{ startEnd.start }}</button>
    <button>XXX</button>
    <button class="active">{{ pageNo }}</button>
    <button>XXX</button>
    <button>{{ startEnd.end }}</button> -->
    <button
      v-for="(num, index) in startEnd.end - startEnd.start + 1"
      :key="index"
      :class="{ active: pageNo === startEnd.start + index }"
      @click="changePageNum(startEnd.start + index)"
    >
      {{ startEnd.start + index }}
    </button>
    <span v-if="startEnd.end < pageTotal - 1">···</span>
    <button v-if="startEnd.end !== pageTotal" @click="changePageNum(pageTotal)">{{ pageTotal }}</button>
    <button :disabled="pageNo === pageTotal" @click="changePageNum(pageNo + 1)">下一页</button>

    <span>共 {{ total }} 条</span>
  </div>
</template>

<script>
export default {
  name: 'SphPagination',
  props: {
    // 总条数
    total: {
      type: Number,
      required: true
    },
    // 每页展示条数
    pageSise: {
      type: Number,
      default: 5
    },
    // 当前页码
    pageNo: {
      type: Number,
      require: true,
      default: 1
    },
    // 相邻页码展示数
    continues: {
      type: Number,
      require: true,
      default: 5
    }
  },
  computed: {
    pageTotal() {
      return Math.ceil(this.total / this.pageSise)
    },
    startEnd() {
      const { total, pageSize, pageNo, continues, pageTotal } = this
      console.log(total, pageSize)
      let start = 0
      let end = 0
      if (continues > pageTotal) {
        start = 1
        end = pageTotal
      } else {
        start = pageNo - (continues - 1) / 2
        end = pageNo + (continues - 1) / 2
        if (start < 1) {
          start = 1
          end = continues
        }
        if (end > pageTotal) {
          start = pageTotal - continues + 1
          end = pageTotal
        }
      }

      return { start, end }
    }
  },
  methods: {
    changePageNum(newPage) {
      this.$emit('changePageNum', newPage)
    }
  }
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;

  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: gray;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }

  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>
